// Modules to control application life and create native browser window
const {
	app,
	BrowserWindow,
	screen,
	ipcMain
} = require('electron')
const path = require('node:path')
const fs = require("fs");
const {
	count
} = require('node:console');

let mainWindow;

function createWindow() {
	// Create the browser window.
	const screenSize = screen.getPrimaryDisplay().workAreaSize;
	mainWindow = new BrowserWindow({
		width: screenSize.width,
		height: screenSize.height,
		transparent: true,
		resizable: false,
		fullscreen: true,
		skipTaskbar: true,
		frame: false,
		webPreferences: {
			//preload: path.join(__dirname, 'preload.js'),
			devTools: false,
			nodeIntegration: true,
			enableRemoteModule: true,
			contextIsolation: false
		}
	});

	// and load the index.html of the app.
	mainWindow.loadFile('index.html');
	mainWindow.setIgnoreMouseEvents(true, {
		forward: true
	});

	mainWindow.webContents.on("did-finish-load", load);

	// Open the DevTools.
	mainWindow.webContents.openDevTools();
}

Date.prototype.format = function(fmt){
	const o = {
		"y+": this.getFullYear(),					//年
		"M+": this.getMonth()+1,					//月
		"d+": this.getDate(),						//日
		"h+": this.getHours(),						//时
		"m+": this.getMinutes(),					//分
		"s+": this.getSeconds(),					//秒
		"q+": Math.floor((this.getMonth()+3)/3),	//季度
		"S": this.getMilliseconds()					//毫秒
	};
	/* if ( /(y+)/.test(fmt) )
		fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); */
	for (const [i,v] of Object.entries(o))
		if ( new RegExp("("+ i +")").test(fmt) )
			fmt = fmt.replace(RegExp.$1, (v+"").padStart(RegExp.$1.length, "0")); //(RegExp.$1.length==1)? v: ("00"+ v).substr((""+ v).length)
	return fmt;
};

function load() {
	const dataPath = __dirname; //app.isPackaged ? path.join(__dirname, "resources/app") : __dirname;
	const datasetPath = path.join(dataPath, "dataset.csv");
	const countPath = path.join(dataPath, "count.json");
	const preferencePath = path.join(dataPath, "preference.txt");
	const todayPath = path.join(dataPath, "today.txt");
	console.log(dataPath)

	//读取数据集
	const file = fs.readFileSync(datasetPath).toString();
	const dataset = file.split("\n").filter(v => v).map(line => {
		return line.trim().split(",")
	}).filter(v => v[2]);
	console.log(dataset)
	
	//偏好
	if (fs.existsSync(preferencePath)){
		const select = fs.readFileSync(preferencePath).toString();
		mainWindow.webContents.send("data", {
			dataset,
			select
		});
		console.log("[preference]", {
			select
		})
		return;
	}
	
	//today
	if (fs.existsSync(todayPath)){
		const [date, select] = fs.readFileSync(todayPath).toString().split(",");
		const today = new Date().format("yyyy-MM-dd");
		if (date == today){
			mainWindow.webContents.send("data", {
				dataset,
				select
			});
			console.log("[preference]", {
				select
			})
			return;
		}
	}
	
	//计数
	if (!fs.existsSync(countPath)) {
		//计数
		const counter = {};
		for (const [id, name, words] of dataset)
			counter[name] = 0;
		fs.writeFileSync(countPath, JSON.stringify(counter));

		//选择
		const len = dataset.length;
		const select = ~~(Math.random() * len);
		counter[min[select]]++;
		fs.writeFileSync(countPath, JSON.stringify(counter))
		
		//今日
		const today = new Date().format("yyyy-MM-dd");
		fs.writeFileSync(todayPath, [today, min[select]].join(","));
		
		mainWindow.webContents.send("data", {
			dataset,
			select: dataset[select][1]
		});
		console.log("[New File]", {
			len,
			select,
			counter
		})
		
	} else {
		//计数
		const file = fs.readFileSync(countPath).toString();
		const counter = JSON.parse(file);
		let minValue = Infinity,
			min = [];
		for (const [name, count] of Object.entries(counter))
			if (count < minValue) {
				minValue = count;
				min = [name];
			} else if (count == minValue) {
			min.push(name);
		}

		//选择
		const len = min.length;
		const select = ~~(Math.random() * len);
		counter[min[select]]++;
		fs.writeFileSync(countPath, JSON.stringify(counter));
		
		//今日
		const today = new Date().format("yyyy-MM-dd");
		fs.writeFileSync(todayPath, [today, min[select]].join(","));
		
		mainWindow.webContents.send("data", {
			dataset,
			select: min[select]
		});
		console.log("[Existed File]", {
			len,
			select,
			counter
		})
	}
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
	createWindow()

	app.on('activate', function() {
		// On macOS it's common to re-create a window in the app when the
		// dock icon is clicked and there are no other windows open.
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function() {
	if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.